package com.ibeeking.gmc.global.g.rest.service.impl;

import com.ibeeking.gmc.global.g.rest.service.IRedisService;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.json.JsonUtils;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * RedisServiceImpl
 *
 * @Author ibeeking
 * @Date 2020-12-02 16:06
 */
@Service
public class RedisServiceImpl implements IRedisService {
    @Resource
    private Jedis jedis;
    private static final String STAR = "*";

    @Override
    public String view(Integer database, String key) {
        jedis.select(database);

        return JsonUtils.toJsonStr(jedis.get(key));
    }

    @Override
    public List<String> viewByPrefix(Integer database, String keyPrefix) {
        if (keyPrefix.contains(STAR)) {
            return Collections3.emptyList();
        }
        jedis.select(database);

        Set<String> keys = jedis.keys(keyPrefix + STAR);
        List<String> list = new ArrayList<>();
        if (Collections3.isNotEmpty(keys)) {
            for (String key : keys) {
                list.add(key + "==>" + JsonUtils.toJsonStr(jedis.get(key)));
            }
        }
        return list;
    }

    @Override
    public Boolean delOne(Integer database, String key) {
        jedis.select(database);
        jedis.del(key);
        LogUtils.info("delOne删除redis分区:{},key:{}", database, key);
        return true;
    }

    @Override
    public Boolean delByPrefix(Integer database, String keyPrefix) {
        if (keyPrefix.contains(STAR)) {
            return false;
        }
        jedis.select(database);
        Set<String> keys = jedis.keys(keyPrefix + STAR);
        if (Collections3.isNotEmpty(keys)) {
            for (String key : keys) {
                jedis.del(key);
            }
        }
        LogUtils.info("delByPrefix删除redis分区:{},key前缀:{}", database, keyPrefix);
        return true;
    }
}
